/**
 * 下载网页图片
 * @param uri  图片地址
 * @returns {*}
 */
import { Platform} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import RNFS from 'react-native-fs';
import AsyncStorage from "@react-native-async-storage/async-storage";
import SimpleToast from "react-native-simple-toast";
import Clipboard from "@react-native-community/clipboard";
import Toast from "react-native-simple-toast";

export const DownloadImage= async (uri: string) => {
    const lang = await AsyncStorage.getItem('@lang');
    let Tip = "";
    console.log(`DownloadImage:` + uri)
    if (!uri) return null;
    return new Promise((resolve, reject) => {
        let timestamp = (new Date()).getTime();//获取当前时间错
        let random = String(((Math.random() * 1000000) | 0))//六位随机数
        let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //外部文件，共享目录的绝对路径（仅限android）
        const downloadDest = `${dirs}/${timestamp + random}.jpg`;
        const formUrl = uri;
        const options = {
            fromUrl: formUrl,
            toFile: downloadDest,
            background: true,
            begin: (res: any) => {
                console.log('begin', res);
                console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
            },
        };
        try {
            const ret = RNFS.downloadFile(options);
            ret.promise.then((res: any) => {
                // console.log('success', res);
                // console.log('file://' + downloadDest)
                let promise = CameraRoll.saveToCameraRoll(downloadDest);
                promise.then(function (result) {
                    if (lang == "zh")
                        Tip = '保存成功！地址如下：\n' + result;
                    else
                        Tip = "Successfully saved! The address is as follows：\n" + result;
                    SimpleToast.show(Tip);
                }).catch(function (error) {
                    if (lang == "zh")
                        Tip = '保存失败';
                    else
                        Tip = "error";
                    SimpleToast.show(Tip);
                    console.log(error)
                });
                resolve(res);
            }).catch((err: any) => {
                reject(new Error(err))
            });
        } catch (e) {
            reject(new Error(e))
        }

    })

}

export const rgb = () => {//rgb颜色随机
    let r = Math.floor(Math.random()*256);
    let g = Math.floor(Math.random()*256);
    let b = Math.floor(Math.random()*256);
    let rgb = 'rgb('+r+','+g+','+b+')';
    return rgb;
}

export const timeFormat = (t: number|string) => {
    // var z = new Date(t);

    // let M: any = z.getMonth() + 1;
    // if (M < 10) {
    //   M = `0${M}`;
    // }
    // let d: any = z.getDay();
    // if (d < 10) {
    //   d = `0${d}`;
    // }
    // let h: any = z.getHours();
    // if (h < 10) {
    //   h = `0${h}`;
    // }
    // let m: any = z.getMinutes();
    // if (m < 10) {
    //   m = `0${m}`;
    // }
    // let s: any = z.getSeconds();
    // if (s < 10) {
    //   s = `0${s}`;
    // }
    // return `${z.getFullYear()}-${M}-${d} ${h}:${m}:${s}`;
    t = Number(t)
    let date = new Date(t);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let year = date.getFullYear(),
        month = ("0" + (date.getMonth() + 1)).slice(-2),
        sdate = ("0" + date.getDate()).slice(-2),
        hour = ("0" + date.getHours()).slice(-2),
        minute = ("0" + date.getMinutes()).slice(-2),
        second = ("0" + date.getSeconds()).slice(-2);
    return year + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
}

export const setCopyMsg = (message:string) => {
    Clipboard.setString(message);
    Toast.show(message+" 已复制");
    return;
}
export const ArrayIsEqual = (arr1:any,arr2:any) => {//判断2个数组是否相等
    if(arr1===arr2){//如果2个数组对应的指针相同，那么肯定相等，同时也对比一下类型
        return true;
    }else{
        if(arr1.length!=arr2.length){
            return false;
        }else{//长度相同
            for(let i in arr1){//循环遍历对比每个位置的元素
                if(arr1[i]!=arr2[i]){//只要出现一次不相等，那么2个数组就不相等
                    return false;
                }
            }//for循环完成，没有出现不相等的情况，那么2个数组相等
            return true;
        }
    }
}
